import chalk from 'chalk'
import _ from 'lodash'
import {article, section} from './lablog.js'
import {Maybe, join, map, add} from './util.js'

// 将 map/join 的操作打包到一个单独的函数中。这就是 chain, 更准确的名字是： flatMap
const chain = _.curry((f, m) => {
    return m.map(f).join()
})

const addressInfo = {
    addresses: [
        {
            street: "LuYe"
        }
    ]
}
const safeProp = _.curry((prop, obj) => {
    return Maybe.of(obj[prop])
})
const safeHead = safeProp(0)

console.group(chalk.bgBlue("chain basic test"))
// map/join
const mapjoinResult = _.flowRight(
    join,
    map(safeProp("street")),
    join,
    map(safeHead),
    safeProp("addresses"),
)
console.log(mapjoinResult(addressInfo))

// chain
const chainResultF = _.flowRight(
    chain(safeProp('street')),
    chain(safeHead),
    safeProp("addresses"),
)
console.log(chainResultF(addressInfo))

console.groupEnd()

const m1 = Maybe.of(3).chain(function(three) {
    return Maybe.of(2).map(add(three))
})
console.log(m1)
const m2 = Maybe.of(null).chain(safeProp('address')).chain(safeProp('street'))
console.log(m2)